var start=null,countdown=require('../public/javascripts/countdown'),sdc = require('sdc-clients'),dc_config=require('../config/dc')['poc'],vmapi = new sdc.VMAPI(dc_config.vmapi),readline = require('readline'),rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout
})

rl.question('请输入owner_uuid(customer):\n', function(answer) {
	rl.close()
	start=new Date()
	var user_id=answer||'7e5f0cd3-5241-601d-d146-9d93c7af0e1b'
	vmapi.listVms({"query":"(&(state=running)(owner_uuid="+user_id+"))"},function(err, vms){
		if (err)err(err)
		else serializeDelete(vms,user_id)
	})
})
function serializeDelete(vms,user_id){
	if(vms.length){
		console.log('\n序列化删除第'+vms.length+'台主机')
		var begin=new Date()
		vmapi.deleteVm({creator_uuid:user_id,uuid:vms.pop().uuid},function (err, obj) {
			var end=new Date()
			if(err){
				err(err)
				serializeDelete(vms,user_id)
			}else{
				console.log('第'+(vms.length+1)+'台主机已删除，uuid：'+obj.vm_uuid,
					'，api响应时间：',countdown(end,begin,countdown.ALL).toString(),
					'('+begin.getTime()+'~'+end.getTime()+')')
				setTimeout(function(){cometState(obj.vm_uuid,'',0,vms,user_id,begin)},500)
			}
		})
	}else{
		console.log('\n所有主机删除完毕，总耗时：',countdown(new Date(),start,countdown.ALL).toString())
		process.exit(1)
	}
}
function err(err){
	if(err.body&&err.body.errors)
		for(var e in err.body.errors)
			console.log(err.body.errors[e])
	else console.log(err)
}
function cometState(vm_uuid,state,i,vms,user_id,begin){
	vmapi.getVm({uuid:vm_uuid},function(err, vm){
		if (err)err(err)
		else if(vm.state){
			if(state!=vm.state){
				state=vm.state
				console.log(state)
			}
			if(state!='destroyed'&&i<50){
				setTimeout(function(){cometState(vm_uuid,state,++i,vms,user_id,begin)},500)
			}
			else{
				var end=new Date()
				if(state!='destroyed')console.log('Time out！')
				console.log('轮询'+i+'次,耗时:',countdown(end,begin,countdown.ALL).toString(),'IP:',vm.nics?vm.nics[0].ip:'null')
				serializeDelete(vms,user_id)
			}
		}
	})
}